import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
import Home from '../views/home.vue'
import store from "@/store";
import {Tool} from "@/util/tool";
// import About from "../views/about.vue";
// import AdminEbook from "../views/admin/admin-ebook.vue";
// import AdminCategory from "../views/admin/admin-category.vue";
// import AdminDoc from "../views/admin/admin-doc.vue";
// import Doc from "../views/doc.vue";
// import User from "../views/admin/admin-user.vue";
// import AdminStatistic from "@/views/admin/admin-statistic.vue";

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: () => import('../views/about.vue')
    },
    {
        path: '/admin/ebook',
        name: 'AdminEbook',
        component: () => import('../views/admin/admin-ebook.vue'),
        meta: {//meta:自定义数据
            loginRequire: true
        }
    },
    {
        path: '/admin/category',
        name: 'AdminCategory',
        component: () => import('../views/admin/admin-category.vue'),
        meta: {
            loginRequire: true
        }
    },
    {
        path: '/admin/doc',
        name: 'AdminDoc',
        component: () => import('../views/admin/admin-doc.vue'),
        meta: {
            loginRequire: true
        }
    },
    {
        path: '/doc',
        name: 'Doc',
        component: () => import('../views/doc.vue'),
    },
    {
        path: '/admin/user',
        name: 'User',
        component: () => import('../views/admin/admin-user.vue'),
        meta: {
            loginRequire: true
        }
    },
    {
        path: '/admin/statistic',
        name: 'AdminStatistic',
        component: () => import('../views/admin/admin-statistic.vue'),
        meta: {
            loginRequire: true
        }
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// 路由登录拦截
router.beforeEach((to, from, next) => {
    // 要不要对meta.loginRequire属性做监控拦截
    if (to.matched.some(function (item) {
        console.log(item, "是否需要登录校验：", item.meta.loginRequire);
        return item.meta.loginRequire
    })) {
        const loginUser = store.state.user;
        if (Tool.isEmpty(loginUser)) {
            console.log("用户未登录！");
            next('/');
        } else {
            next();
        }
    } else {
        next();
    }
});

export default router
